package com.gxc.datacore.metadata.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.gxc.datacore.db.dialect.Dialect;
import com.gxc.datacore.metadata.domain.Database;
import com.gxc.datacore.metadata.domain.DatabaseType;
import com.gxc.datacore.metadata.service.DatabaseService;
import com.gxc.datacore.metadata.service.DatabaseTypeService;
import com.gxc.dbcore.dao.SqlDao;
import com.gxc.webcore.util.ContextUtil;

/**
 * 数据源里的元数据信息采集工具类
 * 
 * @author gxc
 * 
 */
public class CollectUtil {

	@SuppressWarnings("rawtypes")
	private static Map cache = new HashMap();

	@SuppressWarnings("unchecked")
	public static Dialect getDialect(Database database) {
		Dialect dialect = null;
		if (database != null) {
			DatabaseTypeService typeService = (DatabaseTypeService) ContextUtil
					.getBean(DatabaseTypeService.class);
			DatabaseType type = typeService.retrieve(database.getDb_type());
			dialect = (Dialect) cache.get(type.getDialect_class());
			if (dialect == null) {
				try {
					dialect = (Dialect) Class.forName(type.getDialect_class())
							.newInstance();
				} catch (Exception e) {
					e.printStackTrace();
				}
				cache.put(type.getDialect_class(), dialect);
			}
		}
		return dialect;
	}

	/**
	 * 获取数据源中可以访问的所有表
	 * 
	 * @param database_id
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static List getTables(String database_id) {
		DatabaseService databaseService = (DatabaseService) ContextUtil
				.getBean(DatabaseService.class);
		Database database = databaseService.retrieve(database_id);
		return getTables(database);
	}

	/**
	 * 获取数据源中可以访问的所有表
	 * 
	 * @param database
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static List getTables(Database database) {
		Dialect dialect = getDialect(database);
		SqlDao sqlDao = SqlDaoUtil.getSqlDaoByDatabase(database);
		if (dialect != null && sqlDao != null) {
			return dialect.listTables(sqlDao);
		}
		return null;
	}

	/**
	 * 获取表的列信息
	 * 
	 * @param database_id
	 * @param schema_name
	 * @param table_name
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static List getColumns(String database_id, String schema_name,
			String table_name) {
		DatabaseService databaseService = (DatabaseService) ContextUtil
				.getBean(DatabaseService.class);
		Database database = databaseService.retrieve(database_id);
		return getColumns(database, schema_name, table_name);
	}

	/**
	 * 获取表的列信息
	 * 
	 * @param database
	 * @param schema_name
	 * @param table_name
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static List getColumns(Database database, String schema_name,
			String table_name) {
		Dialect dialect = getDialect(database);
		SqlDao sqlDao = SqlDaoUtil.getSqlDaoByDatabase(database);
		if (dialect != null && sqlDao != null) {
			return dialect.listColumns(sqlDao, schema_name, table_name);
		}
		return null;
	}

}
